package com.itcam.cm.order.service.impl;

import com.itcam.cm.feign.cart.CartFeignClient;
import com.itcam.cm.feign.user.UserFeignClient;
import com.itcam.cm.model.dto.order.OrderInfoDto;
import com.itcam.cm.model.entity.cart.CartInfo;
import com.itcam.cm.model.entity.order.OrderInfo;
import com.itcam.cm.model.entity.order.OrderItem;
import com.itcam.cm.model.entity.order.OrderLog;
import com.itcam.cm.model.entity.product.ProductSku;
import com.itcam.cm.model.entity.user.AuthContextUtil;
import com.itcam.cm.model.entity.user.UserAddress;
import com.itcam.cm.model.entity.user.UserInfo;
import com.itcam.cm.model.vo.order.TradeVo;
import com.itcam.cm.order.mapper.OrderInfoMapper;
import com.itcam.cm.order.mapper.OrderItemMapper;
import com.itcam.cm.order.mapper.OrderLogMapper;
import com.itcam.cm.order.service.OrderInfoService;
import com.itcam.cm.feign.product.ProductFeignClient;
import com.itcam.cm.util.ItcamAssert;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderInfoServiceImpl implements OrderInfoService {

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    CartFeignClient cartFeignClient;

    @Autowired
    OrderLogMapper orderLogMapper;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    ProductFeignClient productFeignClient;

    @Override
    public TradeVo getTrade() {

        UserInfo user = AuthContextUtil.getUser();
        Long userId = user.getId();
        List<CartInfo> cartInfos = cartFeignClient.getAllChecked();// 通过feign传递用户信息给拦截器

        TradeVo tradeVo = new TradeVo();
        List<OrderItem> orderItemList = new ArrayList<>();
        for (CartInfo cartInfo : cartInfos) {        // 将购物项数据转换成功订单明细数据
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItem.setThumbImg(cartInfo.getImgUrl());
            orderItemList.add(orderItem);
        }
        // 计算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderInfoDto orderInfoDto) {
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        BigDecimal feightFee = orderInfoDto.getFeightFee();
        Long userAddressId = orderInfoDto.getUserAddressId();
        String remark = orderInfoDto.getRemark();// 备注
        UserInfo user = AuthContextUtil.getUser();

        // 调用user服务，获得地址信息(feign)
        UserAddress userAddress = userFeignClient.getUserAddress(userAddressId);

        // 插入订单信息order_info
        OrderInfo orderInfo = new OrderInfo();
        String no = String.valueOf(System.currentTimeMillis());
        orderInfo.setOrderNo("itcam" + no);// 生成订单号，外部通用订单号
        orderInfo.setUserId(user.getId());
        orderInfo.setNickName(user.getUsername());
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());
        orderInfo.setPayType(2);//2 支付宝
        orderInfo.setOrderStatus(0);// 0 未支付
        orderInfoMapper.insertOrderInfo(orderInfo);
        Long orderInfoId = orderInfo.getId();

        // 插入订单详情order_item,调用product服务，查询库存(feign)
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfoId);
            // 检查库存是否超卖
            Integer skuNum = orderItem.getSkuNum();
            // 调用product服务，查询库存(feign)
            ProductSku productSku = productFeignClient.getSkuById(orderItem.getSkuId());
            ItcamAssert.isTrue(skuNum <= productSku.getStockNum(), "库存不足");
            orderItemMapper.insertOrderItem(orderItem);
        }

        // 插入订单日志order_log
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insertOrderLog(orderLog);

        // 清空购物车(feign)
        cartFeignClient.deleteCheckedCart();

        return orderInfoId;

    }

    @Override
    public TradeVo buy(Long skuId) {
        UserInfo user = AuthContextUtil.getUser();
        Long userId = user.getId();
        ProductSku productSku = productFeignClient.getSkuById(skuId);

        TradeVo tradeVo = new TradeVo();
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItemList.add(orderItem);

        // 计算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));

        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public OrderInfo getOrderById(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        return orderInfo;
    }

    @Override
    public PageInfo<OrderInfo> findOrderPage(Integer page, Integer limit, Integer orderStatus) {
        PageHelper.startPage(page, limit);
        Long userId = AuthContextUtil.getUser().getId();
        List<OrderInfo> orderInfoList = orderInfoMapper.selectOrderPage(userId, orderStatus);
        return new PageInfo<>(orderInfoList);
    }

    @Override
    public OrderInfo getOrderByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectByOrderNo(orderNo);
        List<OrderItem> orderItems = orderItemMapper.selectByOrderId(orderInfo.getId());
        orderInfo.setOrderItemList(orderItems);
        return orderInfo;
    }
}
